package tmc.app.main;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import tmc.app.admin.ActivityAdmin;
import tmc.app.admin.ActivityLoginAdmin;
import tmc.app.data.DBHandler;
import tmc.app.data.GlobalVariables;
import tmc.app.data.ObjRecordData;
import tmc.app.data.ObjUser;
import tmc.app.data.ProcessData;
import tmc.app.login.ActivityLogin;
import tmc.app.luckydraw.R;
import tmc.app.luckydraw.StarshipView;
import tmc.app.luckydraw.R.layout;
import tmc.app.luckydraw.R.menu;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {

	private ImageView img_play;
	private ImageView img_next;
	private ImageView img_admin;
	private GestureDetector gestureDetector;
	// private GestureDetector gestureDetector2;
	boolean tapped;
	private Context mContext;
	private DBHandler db;
	private Activity mActivity;
	private ImageView img_animation_beer;
	private Spinner spinner;
	private String[] quanArray;
	private Dialog mDialog;
	private int quanTam;
	private ImageView img_dongbo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro);

		mContext = this;
		mActivity = this;
		db = new DBHandler(mContext);
		gestureDetector = new GestureDetector(mContext, new GestureListener());
		// gestureDetector2 = new GestureDetector(mContext, new
		// GestureListener2());
		initLayout();
		initEvents();
		onLoadData();
		// db.deleteAllItemsRecordData();
		animationBeer();

	}

	public void animationBeer() {
		img_animation_beer.startAnimation(inFromLeftAnimation(2000));
		img_next.startAnimation(inFromLeftAnimation(2500));
		img_play.startAnimation(alphaFadeOut(5000));
	}

	public void onBackPressed() {
	};

	public String getCurrentDate() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String date = df.format(Calendar.getInstance().getTime());

		return date;
	}

	public boolean checkDateRecord(String date, List<ObjRecordData> lst) {
		boolean isFound = false;
		if (lst.size() != 0) {
			for (int i = 0; i < lst.size(); i++) {
				if (lst.get(i).getDate().toString().equals(date)) {
					isFound = true;
					break;
				}
			}
		}

		return isFound;
	}

	public void onLoadData() {
		GlobalVariables.lstData = db.getAllItemsRecordData();

		/*
		 * if(GlobalVariables.lstData.size() != 0) { printDate(); }
		 */
		if (GlobalVariables.lstData.size() == 0) {
			// get data default:
			Log.v("DATA", "first login");
			ObjRecordData data = new ObjRecordData(getCurrentDate(), "75", "1",
					"0", "2", "0", "2", "0", "2", "0", "6", "0");
			// ObjRecordData data = new ObjRecordData(getCurrentDate(),
			// "80","1", "0", "1", "0", "1", "0", "2", "0", "4", "0");

			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.AO,
					Integer.parseInt(data.getDataAo()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.BALO,
					Integer.parseInt(data.getDataBalo()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.VIET,
					Integer.parseInt(data.getDataBut()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.MOC_KHOA,
					Integer.parseInt(data.getDataMockhoa()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.SO_TAY,
					Integer.parseInt(data.getDataSotay()));

			db.insertRecordData(data);
			setDataGame(data);
		} else {
			if (!checkDateRecord(getCurrentDate(), GlobalVariables.lstData)) {
				Log.v("DATA",
						"qua ngay moi " + String.valueOf(getCurrentDate()));

				int ao = GlobalVariables.loadCountGiaiThuong(mActivity,
						GlobalVariables.AO);
				int balo = GlobalVariables.loadCountGiaiThuong(mActivity,
						GlobalVariables.BALO);
				int viet = GlobalVariables.loadCountGiaiThuong(mActivity,
						GlobalVariables.VIET);
				int so_tay = GlobalVariables.loadCountGiaiThuong(mActivity,
						GlobalVariables.SO_TAY);
				int moc_khoa = GlobalVariables.loadCountGiaiThuong(mActivity,
						GlobalVariables.MOC_KHOA);

				ObjRecordData data = new ObjRecordData(getCurrentDate(), "75",
						String.valueOf(ao), "0", String.valueOf(balo), "0",
						String.valueOf(so_tay), "0", String.valueOf(viet), "0",
						String.valueOf(moc_khoa), "0");

				db.insertRecordData(data);
				setDataGame(data);
				GlobalVariables.lstData.clear();
				GlobalVariables.lstData = db.getAllItemsRecordData();
			} else {
				setDataGame(db.getRecordData(getCurrentDate()));
			}
		}
		// printDate();
	}

	public void setDataGame(ObjRecordData data) {
		GlobalVariables.defaultRecordData = data;
	}

	/*
	 * public void printDate() { for(int i = 0; i <
	 * GlobalVariables.lstData.size(); i++) { Log.v("DATA", "items: " + i + " "
	 * + GlobalVariables.lstData.get(i).getDate() + " " +
	 * GlobalVariables.lstData.get(i).getPercent()); } }
	 */

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void initLayout() {
		quanArray = getResources().getStringArray(R.array.quan_arrays);

		spinner = (Spinner) findViewById(R.id.spinner1);
		img_play = (ImageView) findViewById(R.id.img_play);
		img_next = (ImageView) findViewById(R.id.img_next);
		img_admin = (ImageView) findViewById(R.id.img_admin);
		img_animation_beer = (ImageView) findViewById(R.id.img_animation_beer);
		spinner.setOnItemSelectedListener(onItemSelectedListener);
		spinner.setSelection(GlobalVariables.globalLastQuan);
		quanTam = GlobalVariables.globalLastQuan;
		img_dongbo = (ImageView) findViewById(R.id.img_dongbo);
	}

	public OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			if (arg2 != 0) {
				if (GlobalVariables.globalLastQuan != arg2) {
					showDialogLoginQuan(mActivity, quanArray[arg2].toString());
					quanTam = arg2;
					// GlobalVariables.globalLastQuan = arg2;
				}
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}
	};

	private Animation alphaFadeOut(int time) {
		AlphaAnimation animation1 = new AlphaAnimation(0.0f, 1.0f);
		animation1.setDuration(time);
		animation1.setFillAfter(true);
		animation1.setInterpolator(new AccelerateInterpolator());
		return animation1;
	}

	// tu tren xuong
	private Animation downFromUpAnimation(int time) {

		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(time);
		inFromRight.setFillAfter(true);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	// tu tren xuong
	private Animation upFromDownAnimation(int time) {

		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(time);
		inFromRight.setFillAfter(true);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	// phai qua
	private Animation inFromRightAnimation(int time) {

		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(time);
		inFromRight.setFillAfter(true);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	private Animation outToLeftAnimation() {
		Animation outtoLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoLeft.setDuration(500);
		outtoLeft.setInterpolator(new AccelerateInterpolator());
		return outtoLeft;
	}

	// trai qua
	private Animation inFromLeftAnimation(int time) {
		Animation inFromLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromLeft.setDuration(time);
		inFromLeft.setFillAfter(true);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;
	}

	private Animation outToRightAnimation() {
		Animation outtoRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoRight.setDuration(500);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;
	}

	public void initEvents() {
		img_play.setOnClickListener(onClickListener);
//		img_next.setOnClickListener(onClickListener);
		img_admin.setOnTouchListener(onTouchListener);
		img_dongbo.setOnClickListener(onClickListener);
	}

	public OnTouchListener onTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View arg0, MotionEvent arg1) {
			// TODO Auto-generated method stub
			return gestureDetector.onTouchEvent(arg1);
		}
	};

	// public OnTouchListener onTouchListener2 = new OnTouchListener() {
	//
	// @Override
	// public boolean onTouch(View arg0, MotionEvent arg1) {
	// // TODO Auto-generated method stub
	// return gestureDetector2.onTouchEvent(arg1);
	// }
	// };

	public OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.img_play:
				ProcessData.ringPhone(mActivity);
				if (!GlobalVariables.tenquan.equals("")) {
					moveToLogin();
				} else {

					ProcessData.showDialogThongbao(mContext, getResources()
							.getString(R.string.txt_chuachonquan));
				}
				break;
			case R.id.img_dongbo:
				ProcessData.ringPhone(mActivity);
				showDialogDongbo();
				break;
			default:
				break;
			}
		}
	};

	public void moveToLogin() {
		Intent intent = new Intent(this, ActivityLogin.class);
		startActivity(intent);
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		finish();
	}

	public void moveToAdmin() {
		Intent intent = new Intent(this, ActivityLoginAdmin.class);
		startActivity(intent);
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		finish();
	}

	public void resetGiaithuong() {
		// GlobalVariables.globalCount = 0;
	}

	public void showDialogLoginQuan(final Activity mActivity,
			final String tenquan) {
		final Dialog dialog = new Dialog(mContext, android.R.style.Theme_Black);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.activity_login_quan);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.bg_transparent);

		ImageView img_cancel = (ImageView) dialog.findViewById(R.id.img_cancel);
		final EditText pass = (EditText) dialog.findViewById(R.id.pass);
		ImageView img_login = (ImageView) dialog.findViewById(R.id.img_login);
		img_login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ProcessData.ringPhone(mActivity);

				if (!pass.getText().toString().equals("")) {
					if (pass.getText().toString().equals("thangtien@2709")) {

						GlobalVariables.globalLastQuan = quanTam;
						spinner.setSelection(GlobalVariables.globalLastQuan);
						GlobalVariables.tenquan = tenquan;
						resetGiaithuong();
						dialog.dismiss();
					} else {
						// sai pass
						ProcessData.showDialogThongbao(mContext, getResources()
								.getString(R.string.txt_wrongAdmin));
					}
				} else {
					// show dialog
					ProcessData.showDialogThongbao(mContext, getResources()
							.getString(R.string.txt_inputLoginErr));
				}
			}
		});
		img_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				spinner.setSelection(GlobalVariables.globalLastQuan);
				ProcessData.ringPhone(mActivity);
				dialog.dismiss();
			}
		});

		dialog.setCancelable(false);
		dialog.show();
	}

	public class GestureListener extends
			GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onDown(MotionEvent e) {

			return true;
		}

		// event when double tap occurs
		@Override
		public boolean onDoubleTap(MotionEvent e) {

			tapped = !tapped;

			if (tapped) {
				moveToAdmin();
			} else {

			}

			return true;
		}
	}

	public void showDialogDongbo() {
		final Dialog dialog = new Dialog(mActivity, android.R.style.Theme_Black);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.layout_dialog_del);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.bg_transparent);
		Button btnOpt1 = (Button) dialog.findViewById(R.id.btn_yes);
		Button btnOpt2 = (Button) dialog.findViewById(R.id.btn_no);
		TextView txtName = (TextView) dialog.findViewById(R.id.txt_name);

		btnOpt1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// thoat
				ProcessData.ringPhone(mActivity);

				loadRecordUserFromDb();
				loadRecordDataFromDb();
				showDialog();
				onPostToServer();

				dialog.dismiss();
			}
		});

		btnOpt2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ProcessData.ringPhone(mActivity);
				dialog.dismiss();
			}
		});

		dialog.setCancelable(false);
		dialog.show();

	}

	/*
	 * public class GestureListener2 extends
	 * GestureDetector.SimpleOnGestureListener {
	 * 
	 * @Override public boolean onDown(MotionEvent e) {
	 * 
	 * return true; }
	 * 
	 * // event when double tap occurs
	 * 
	 * @Override public boolean onDoubleTap(MotionEvent e) {
	 * 
	 * tapped = !tapped;
	 * 
	 * if (tapped) { //dialog dongbo showDialogDongbo(); } else {
	 * 
	 * }
	 * 
	 * return true; } }
	 */

	public void onPostToServer() {
		if (ProcessData.isInternet(mActivity)) {
			try {
				if (GlobalVariables.lstData.size() != 0) {
					postToServer();
				} else {
					if (GlobalVariables.lstUser.size() != 0) {
						postRecordUserToServer();
					} else {
						closeDialog();
						// deleteAllData();
						// showDialogDeleteData();
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		} else {
			showDialogConnection(0);
		}
	}

	public void showDialogConnection(final int type) {
		final Dialog dialog = new Dialog(mActivity, android.R.style.Theme_Black);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.layout_dialog_internet);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.bg_transparent);
		Button btnOpt1 = (Button) dialog.findViewById(R.id.btn_yes);
		Button btnOpt2 = (Button) dialog.findViewById(R.id.btn_no);
		TextView txtName = (TextView) dialog.findViewById(R.id.txt_name);

		btnOpt1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// thoat
				ProcessData.ringPhone(mActivity);
				System.exit(0);
			}
		});

		btnOpt2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ProcessData.ringPhone(mActivity);
				switch (type) {
				case 0:// loadData
					onPostToServer();
					break;
				}
				dialog.dismiss();
			}
		});

		dialog.setCancelable(false);
		dialog.show();

	}

	public void deleteAllData() {
		db.deleteAllItemsRecordData();
		db.deleteAllRecordUsers();
	}

	public void resetVariblesPost() {
		GlobalVariables.lstData.clear();
		GlobalVariables.index = 0;
		GlobalVariables.id_giai_thuong = 1;
	}

	public void setVariablesPost() {
		GlobalVariables.id_giai_thuong++;
		if (GlobalVariables.id_giai_thuong > 5) {
			GlobalVariables.index++;
			if (GlobalVariables.index < GlobalVariables.lstData.size()) {
				Log.v("TEST",
						"GlobalVariables.index < GlobalVariables.lstData.size - postToServer");
				GlobalVariables.id_giai_thuong = 1;
				if (!getCurrentDate().equals(
						GlobalVariables.lstData.get(GlobalVariables.index)
								.getDate())) {
					db.deleteItemsRecordData(GlobalVariables.lstData
							.get(GlobalVariables.index));
				}
				postToServer();
			} else {
				Log.v("TEST", "resetVariblesPost - postRecordUserToServer");
				resetVariblesPost();
				if (GlobalVariables.lstUser.size() != 0) {
					postRecordUserToServer();
				} else {

					ProcessData.showDialogThongbao(mContext, getResources()
							.getString(R.string.txt_dongboComplete));
					closeDialog();
					// deleteAllData();
					// showDialogDeleteData();
				}
			}
		} else {
			Log.v("TEST", "GlobalVariables.id_giai_thuong <5 - postToServer");
			postToServer();
		}
	}

	public void setVariablePostRecordUser() {
		GlobalVariables.indexUser++;
		if (GlobalVariables.indexUser < GlobalVariables.lstUser.size()) {
			postRecordUserToServer();
		} else {
			GlobalVariables.lstUser.clear();
			GlobalVariables.indexUser = 0;
			// postCompleted = true;
			// deleteAllData();
			closeDialog();
			ProcessData.showDialogThongbao(mContext,
					getResources().getString(R.string.txt_dongboComplete));
			// showDialogDeleteData();
			Log.v("TEST", "complete");
		}
	}

	public void postToServer() {
		try {
			onLoadDataToServer(GlobalVariables.id_giai_thuong,
					GlobalVariables.lstData.get(GlobalVariables.index));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void onLoadDataToServer(int id_giai_thuong, ObjRecordData recordData) {
		try {
			new LoadDataDataToServer(id_giai_thuong, recordData).execute();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	class LoadDataDataToServer extends AsyncTask<Void, Void, JSONObject> {
		private int id_giai_thuong;
		private ObjRecordData recordData;

		public LoadDataDataToServer(int id_giai_thuong, ObjRecordData recordData) {
			this.id_giai_thuong = id_giai_thuong;
			this.recordData = recordData;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected JSONObject doInBackground(Void... params) {
			JSONObject data = ProcessData.postRecordData(id_giai_thuong,
					recordData);
			return data;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			// Log.v("TEST", "data get edit: " + result);
			if (result != null) {
				String status;
				try {
					status = result.getString("status");

					if (status.equals("true")) {
						setVariablesPost();
					} else {

						closeDialog();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {

				closeDialog();
			}

			super.onPostExecute(result);
		}
	}

	public void postRecordUserToServer() {
		try {
			onLoadDataUserToServer(GlobalVariables.lstUser
					.get(GlobalVariables.indexUser));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void onLoadDataUserToServer(ObjUser recordUser) {
		try {
			new LoadDataUserToServer(recordUser).execute();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	class LoadDataUserToServer extends AsyncTask<Void, Void, JSONObject> {
		private ObjUser recordUser;

		public LoadDataUserToServer(ObjUser recordUser) {
			this.recordUser = recordUser;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected JSONObject doInBackground(Void... params) {
			JSONObject data = ProcessData.postRecordUser(recordUser);
			return data;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			// Log.v("TEST", "data get edit: " + result);
			if (result != null) {
				String status;
				try {
					status = result.getString("status");

					if (status.equals("true")) {
						// delete items
						db.deleteItemsRecordUsers(recordUser);
						setVariablePostRecordUser();
					} else {

						closeDialog();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {

				closeDialog();
			}

			super.onPostExecute(result);
		}
	}

	public void loadRecordUserFromDb() {
		GlobalVariables.indexUser = 0;
		GlobalVariables.lstUser.clear();
		GlobalVariables.lstUser = db.getAllItemsRecordUser();
	}

	public void loadRecordDataFromDb() {
		resetVariblesPost();
		GlobalVariables.lstData.clear();
		GlobalVariables.lstData = db.getAllItemsRecordData();
	}

	public void showDialog() {
		if (mActivity != null) {
			if (mDialog != null)
				mDialog.dismiss();
			mDialog = new Dialog(mActivity,
					android.R.style.Theme_Translucent_NoTitleBar);
		}
		if (mDialog != null)
			ProcessData.showDialogLoading(mDialog, "");
	}

	public void closeDialog() {
		if (mDialog != null)
			mDialog.dismiss();
	}
}
